package com.justgame.project.cloud.common.util;

import com.alibaba.fastjson.JSONObject;
import com.justgame.project.cloud.common.exception.Exc;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * HTTP解析工具
 */
@Slf4j
@Component
public class HttpContextUtil {

    public static String BaiduLocationApi;

    public static HttpServletRequest getHttpRequest() {
        try {
            return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        } catch (NullPointerException nullPointerException) {
            throw new Exc("无法解析HTTP请求！");
        }
    }

    public static HttpServletResponse getHttpResponse() {
        try {
            return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
        } catch (NullPointerException nullPointerException) {
            throw new Exc("无法获取Response！");
        }
    }

    public static String getBodyString(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        InputStream inputStream = null;
        BufferedReader reader = null;
        try {
            inputStream = request.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

    public static HttpSession getSession() {
        return getHttpRequest().getSession();
    }

    public static String getDomain() {
        HttpServletRequest request = getHttpRequest();
        //   例如：http://localhost:8080/abc123/
        StringBuffer url = request.getRequestURL();
        //   获得如上"例如"的 http://localhost:8080
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
    }

    public static String getOrigin() {
        HttpServletRequest request = getHttpRequest();
        return request.getHeader("Origin");
    }

    public static String getIp() {
        return getIp(getHttpRequest());
    }

    // 方法1
    private static String getNowIP1() throws IOException {
        String ip = null;
        String chinaz = "http://ip.chinaz.com";
        StringBuilder inputLine = new StringBuilder();
        String read = "";
        URL url = null;
        HttpURLConnection urlConnection = null;
        BufferedReader in = null;
        try {
            url = new URL(chinaz);
            urlConnection = (HttpURLConnection) url.openConnection();
            in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), StandardCharsets.UTF_8));
            while ((read = in.readLine()) != null) {
                inputLine.append(read).append("\r\n");
            }
            Pattern p = Pattern.compile("\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");
            Matcher m = p.matcher(inputLine.toString());
            if (m.find()) {
                ip = m.group(1);
            }
        } finally {
            if (in != null) {
                in.close();
            }
        }
        if ("".equals(ip)) {
            throw new RuntimeException();
        }
        return ip;
    }
    // 方法2
    private static String getNowIP2() throws IOException {
        String ip = null;
        BufferedReader br = null;
        try {
            URL url = new URL("https://v6r.ipip.net/?format=callback");
            br = new BufferedReader(new InputStreamReader(url.openStream()));
            String s = "";
            StringBuilder sb = new StringBuilder("");
            String webContent = "";
            while ((s = br.readLine()) != null) {
                sb.append(s).append("\r\n");
            }
            webContent = sb.toString();
            int start = webContent.indexOf("(") + 2;
            int end = webContent.indexOf(")") - 1;
            webContent = webContent.substring(start, end);
            ip = webContent;
        } finally {
            if (br != null)
                br.close();
        }
        if ("".equals(ip)) {
            throw new RuntimeException();
        }
        return ip;
    }
    // 方法3
    private static String getNowIP3() throws IOException {
        String ip = null;
        String objWebURL = "https://ip.900cha.com/";
        BufferedReader br = null;
        try {
            URL url = new URL(objWebURL);
            br = new BufferedReader(new InputStreamReader(url.openStream()));
            String s = "";
            String webContent = "";
            while ((s = br.readLine()) != null) {
                if (s.contains("我的IP:")) {
                    ip = s.substring(s.indexOf(":") + 1);
                    break;
                }
            }
        } finally {
            if (br != null)
                br.close();
        }
        if ("".equals(ip)) {
            throw new RuntimeException();
        }
        return ip;
    }
    // 方法4
    private static String getNowIP4() throws IOException {
        String ip = null;
        String objWebURL = "https://bajiu.cn/ip/";
        BufferedReader br = null;
        try {
            URL url = new URL(objWebURL);
            br = new BufferedReader(new InputStreamReader(url.openStream()));
            String s = "";
            String webContent = "";
            while ((s = br.readLine()) != null) {
                if (s.contains("互联网IP")) {
                    ip = s.substring(s.indexOf("'") + 1, s.lastIndexOf("'"));
                    break;
                }
            }
        } finally {
            if (br != null)
                br.close();
        }
        if ("".equals(ip)) {
            throw new RuntimeException();
        }
        return ip;
    }
    /**
     * 获取本机外网IPv4地址
     */
    @SuppressWarnings("all")
    public static String getPublicIP() {
        String ip = null;
        // 第一种方式
        try {
            ip = getNowIP1();
            ip.trim();
        } catch (Exception ignored) {}
        if (StringUtils.isNotBlank(ip))
            return ip;
        // 第二种方式
        try {
            ip = getNowIP2();
            ip.trim();
        } catch (Exception ignored) {}
        if (StringUtils.isNotBlank(ip))
            return ip;
        // 第三种方式
        try {
            ip = getNowIP3();
            ip.trim();
        } catch (Exception ignored) {}
        if (StringUtils.isNotBlank(ip))
            return ip;
        // 第四种方式
        try {
            ip = getNowIP4();
            ip.trim();
        } catch (Exception ignored) {}
        if (StringUtils.isNotBlank(ip))
            return ip;
        return ip;
    }

    // 多次反向代理后会有多个ip值 的分割符
    private final static String IP_UTILS_FLAG = ",";
    // 未知IP
    private final static String UNKNOWN = "unknown";
    // 本地 IP
    private final static String LOCALHOST_IP = "0:0:0:0:0:0:0:1";
    private final static String LOCALHOST_IP1 = "127.0.0.1";


    public static String getIP(ServerHttpRequest request){
        // 根据 HttpHeaders 获取 请求 IP地址
        String ip = request.getHeaders().getFirst("X-Forwarded-For");
        if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("x-forwarded-for");
            if (ip != null && ip.length() != 0 && !UNKNOWN.equalsIgnoreCase(ip)) {
                // 多次反向代理后会有多个ip值，第一个ip才是真实ip
                if (ip.contains(IP_UTILS_FLAG)) {
                    ip = ip.split(IP_UTILS_FLAG)[0];
                }
            }
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("X-Real-IP");
        }
        //兼容k8s集群获取ip
        if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddress().getAddress().getHostAddress();
            if (LOCALHOST_IP1.equalsIgnoreCase(ip) || LOCALHOST_IP.equalsIgnoreCase(ip)) {
                //根据网卡取本机配置的IP
                InetAddress iNet = null;
                try {
                    iNet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    log.error("getClientIp error: ", e);
                }
                ip = iNet.getHostAddress();
            }
        }
        if (ip.contains(",")){
            ip = ip.replaceAll(" ","").split(",")[0];
        }
        return ip;
    }

    public static String getIp(HttpServletRequest request) {
        String ip = null;
        ip = request.getHeader("x-forwarded-for");
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        //使用代理，则获取第一个IP地址
        if (StringUtils.isNotBlank(ip) && ip.length() > 15) {
            if (ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
                log.info("IP:{},为反向代理请求。", ip);
            }
        }
        return ip;
    }

    public static String getRealAddr(String ip){
        if (StringUtils.isBlank(BaiduLocationApi)) {
            return "";
        }
        try {
            if ("127.0.0.1".equals(ip)) {
                return "本地主机";
            }
            URL url = new URL(String.format(BaiduLocationApi, ip));
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);
            connection.connect();
            int code = connection.getResponseCode();
            if (!(code == 200)) {
                return "";
            }
            StringBuilder msg = new StringBuilder();
            // 正常响应
            // 从流中读取响应信息
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            String line = null;
            while ((line = reader.readLine()) != null) { // 循环从流中读取
                msg.append(line);
            }
            reader.close(); // 关闭流
            connection.disconnect();
            Map result = JSONObject.parseObject(msg.toString(), Map.class);
            try {
                return String.valueOf(((Map) result.get("content")).get("address"));
            } catch (NullPointerException e) {
                log.info(e.getMessage());
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String getRealAddr(HttpServletRequest request) {
        String ip = getIp(request);
        return getRealAddr(ip);
    }

    public static String getRealAddr() {
        return getRealAddr(getHttpRequest());
    }

    @Value("${BaiduAPI.getLocation:https://api.map.baidu.com/location/ip?ak=E7xXjxkO8KztQPadYGsyVFyuGXRqCXr4&ip=%s}")
    private void setBaiduApi(String val) {
        HttpContextUtil.BaiduLocationApi = val;
    }
}
